"use strict";

/**
 * @ngdoc service
 * @name jgappApp.getDataService
 * @description
 * # getDataService
 * Service in the jgappApp.
 */
angular.module("jgappApp").factory("DataService", function($http, $q, Util) {
  // AngularJS will instantiate a singleton by calling "new" on this function
  var getDataService = {};
  getDataService.getData = function(url, param, headers) {
    var postData = {};
    var delay = $q.defer();
    if (param && param.cache) {
      var data = Util.getLocalInfo(url);
    }
    if ((data && data.length > 0) || (data && Object.keys(data).length > 0)) {
      delay.resolve(data);
      return delay.promise;
    }
    postData.url = url;
    postData.dataType = "json";
    postData.method = "POST";
    postData.data = param;
    if (headers) {
      postData.headers = headers;
    }
    $http(postData)
      .then(function(data) {
        data=data.data;if (data.logout) {
          Util.logout();
          return;
        }
        if (data.success) {
          if (param && param.cache) {
            Util.saveLocalInfo(url, data.result || data.dataList || data.data);
          }
          delay.resolve(data.result || data.dataList || data.data);
        } else {
          delay.reject("获取用户信息出错");
          Util.Toast(data.result);
        }
      },function(data, stateCode) {
        Util.Toast(
          (stateCode ? "请求出错,错误码" + stateCode : "") ||
            "无法连接到服务器",
          {
            time: 5000
          }
        );
        delay.reject("获取用户信息出错");
      });
    return delay.promise;
  };
  return getDataService;
});
